package com.fwtai.service.api;

import com.fwtai.api.ApiCartsDao;
import com.fwtai.bean.PageFormData;
import com.fwtai.config.LocalUserId;
import com.fwtai.exception.ExceptionCompletion;
import com.fwtai.tool.IdBuilder;
import com.fwtai.tool.ToolClient;
import com.fwtai.tool.ToolString;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.concurrent.CompletableFuture;

/**
 * 购物车
 * @作者 田应平
 * @版本 v1.0
 * @创建时间 2023-09-25 14:51:22
 * @QQ号码 444141300
 * @Email service@fwtai.com
 * @官网 <url>http://www.fwtai.com</url>
*/
@Service
public class ApiCartsService{

  private final ApiCartsDao apiCartsDao;

  private final ThreadPoolTaskExecutor taskExecutor;

  public ApiCartsService(final ApiCartsDao apiCartsDao,final ThreadPoolTaskExecutor taskExecutor){
    this.apiCartsDao = apiCartsDao;
    this.taskExecutor = taskExecutor;
  }

  public String addCarts(final String kid,final String storeId,final String total){
    final Long loginId = LocalUserId.getLong();
    return CompletableFuture.supplyAsync(()->{
      if(loginId == null) return ToolClient.accessLogin();
      final String verifyField = ToolClient.validateField(kid,storeId,total);
      if(verifyField != null) return verifyField;
      final long goodsId = Long.parseLong(kid);//商品的kid
      final int number = Integer.parseInt(total);//商品数量
      if(number < 1){
        return ToolClient.createJsonFail("商品数量有误");
      }
      final HashMap<String,Long> params = new HashMap<>(2);
      params.put("loginId",loginId);
      params.put("goodsId",goodsId);
      final Long cartsId = apiCartsDao.queryGoodsExist(params);//查询是否已加入过购物车(获取购物车的kid)
      //存在就更新数量,否则新增
      if(cartsId != null){
        final HashMap<String,Object> map = new HashMap<>(2);
        map.put("total",number);
        map.put("kid",cartsId);//购物车的kid
        return ToolClient.executeRows(apiCartsDao.updateCartsPlus(map));
      }else{
        //查询价格
        final BigDecimal price = apiCartsDao.queryGoodsPrice(goodsId);
        if(price == null){
          return ToolClient.createJsonFail("商品不存在");
        }
        final HashMap<String,Object> formData = new HashMap<>(5);
        formData.put("kid",new IdBuilder().getId121L());
        formData.put("loginId",loginId);
        formData.put("goodsId",goodsId);
        formData.put("storeId",Long.parseLong(storeId));
        formData.put("total",number);
        formData.put("price",price);
        return ToolClient.executeRows(apiCartsDao.addCarts(formData));
      }
    },taskExecutor).join();
  }

  public String editCarts(final String kid,final String total){
    final Long loginId = LocalUserId.getLong();
    return CompletableFuture.supplyAsync(()->{
      if(loginId == null) return ToolClient.accessLogin();
      final String verifyField = ToolClient.validateField(kid,total);
      if(verifyField != null) return verifyField;
      final HashMap<String,Object> params = new HashMap<>(2);
      try {
        params.put("kid",Long.parseLong(kid));
        final int number = Integer.parseInt(total);
        if(number < 1){
          return ToolClient.createJsonFail("商品数量有误");
        }
        params.put("total",number);
        return ToolClient.executeRows(apiCartsDao.editCarts(params));
      } catch (final Exception ignored) {
        throw new ExceptionCompletion("参数类型有误");
      }
    },taskExecutor).join();
  }

  //因为当 type = 1 是 ids允许为空
  public String delCarts(final String type,final String storeId,final String ids){
    final Long loginId = LocalUserId.getLong();
    return CompletableFuture.supplyAsync(()->{
      if(loginId == null) return ToolClient.accessLogin();
      if(type == null || type.length() == 0){
        return ToolClient.jsonValidateField();
      }
      final int target = Integer.parseInt(type);
      switch (target){
        case 0:
          if(ids == null || ids.length() == 0){//因为当 type = 1 是 ids允许为空,所以要验证
            return ToolClient.jsonValidateField();
          }
          final long[] list = ToolString.keysToArarry(ids);
          if(list == null){
            return ToolClient.createJsonFail("请选择要删除的商品");
          }
          final HashMap<String,Object> params = new HashMap<>(2);
          params.put("loginId",loginId);
          params.put("array",list);//xml映射时的collection="array"也要一致
          return ToolClient.executeRows(apiCartsDao.delByKeys(params),"操作成功","数据不存在,刷新重试");
        case 1:
          if(storeId == null || storeId.length() == 0){
            return ToolClient.jsonValidateField();
          }
          final HashMap<String,Long> delParams = new HashMap<>(2);
          delParams.put("loginId",loginId);
          delParams.put("storeId",Long.parseLong(storeId));
          return ToolClient.executeRows(apiCartsDao.delAllCarts(delParams));
        default:
          return ToolClient.jsonValidateField();
      }
    },taskExecutor).join();
  }

  //含分页
  public String listCarts(final HttpServletRequest request){
    final Long loginId = LocalUserId.getLong();
    return CompletableFuture.supplyAsync(()->{
      if(loginId == null) return ToolClient.accessLogin();
      final PageFormData formData = ToolClient.pageParamsApi(request);
      if(formData == null) return ToolClient.jsonValidateField();
      formData.put("loginId",loginId);
      return ToolClient.jsonPage(apiCartsDao.listCarts(formData));
    },taskExecutor).join();
  }

  //无分页
  public String listCarts(final Long storeId){
    final Long loginId = LocalUserId.getLong();
    return CompletableFuture.supplyAsync(()->{
      if(loginId == null) return ToolClient.accessLogin();
      if(storeId == null) return ToolClient.jsonValidateField();
      final HashMap<String,Long> params = new HashMap<>(2);
      params.put("loginId",loginId);
      params.put("storeId",storeId);
      return ToolClient.queryJson(apiCartsDao.listAllCarts(params));
    },taskExecutor).join();
  }

  public String getCartsTotal(){
    final Long loginId = LocalUserId.getLong();
    return CompletableFuture.supplyAsync(()->{
      if(loginId == null) return ToolClient.accessLogin();
      return ToolClient.queryJson(apiCartsDao.getCartsTotal(loginId));
    },taskExecutor).join();
  }

  public String getStoreId(){
    final Long loginId = LocalUserId.getLong();
    return CompletableFuture.supplyAsync(()->{
      if(loginId == null) return ToolClient.accessLogin();
      return ToolClient.queryJson(apiCartsDao.getStoreId(loginId));
    },taskExecutor).join();
  }

  public String queryStoreGoods(final String storeId,final String goodsId){
    final Long loginId = LocalUserId.getLong();
    return CompletableFuture.supplyAsync(()->{
      if(loginId == null) return ToolClient.accessLogin();
      final String verifyField = ToolClient.validateField(goodsId,storeId);
      if(verifyField != null) return verifyField;
      final HashMap<String,Object> params = new HashMap<>(2);
      params.put("storeId",storeId);
      params.put("goodsId",goodsId);
      return ToolClient.queryJson(apiCartsDao.queryStoreGoods(params));
    },taskExecutor).join();
  }
}